package com.yyl.rbacs.annotation;

import com.alibaba.fastjson.JSON;
import com.yyl.rbacs.sys.entity.SysLog;
import com.yyl.rbacs.sys.entity.SysRole;
import com.yyl.rbacs.sys.entity.SysUser;
import com.yyl.rbacs.sys.service.ISysLogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @BelongsProject: rbacs
 * @BelongsPackage: com.yyl.rbacs.annotation
 * @Author: YuanSir
 * @CreateTime: 2022-11-02  15:15
 * @Description:
 * @Version: 1.0
 */

@Component
@Aspect
public class OperationLogAspect {
    
    @Autowired
    ISysLogService logService;
    
    @Pointcut("@annotation(com.yyl.rbacs.annotation.OperationLog)")
    public void pointCut() {}
    
    
    @Before("pointCut()")
    public void before(JoinPoint jp) {
    
        MethodSignature signature = (MethodSignature) jp.getSignature();
    
        String value = signature.getMethod().getAnnotation(OperationLog.class).value();
    
        Object[] args = jp.getArgs();
    
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        
        List<Object> paramss = Arrays.stream(args)
                .map(o -> {
                    if (o instanceof SysRole){
                        ((SysRole) o).setCreateTime(new Date());
                        return o;
                        }
                    return o;
                })
                .collect(Collectors.toList());
    
        String params = JSON.toJSONString(paramss);
    
        SysLog sysLog = new SysLog(
                user.getUserId(),
                user.getUsername(),
                new Date(),
                value,
                params);
        
        logService.save(sysLog);
        
        
    }
    
}
